"""
Contains classes used for describing movements. Simple movements
can use just move, but movements involving multiple segments should
use a plot, assuming they need validation.
"""

from directions import *
import logging
__all__ = ['plot', 'move']

class plot:
    """
    Represents a plot. Treat as a list. Handles movement validation whenever a
    plot item is added. Not designed for general use.
    """
    owner = None
    data = None
    
    def __init__(self, boat, data=None):
        self.log = logging.getLogger('pgame.engine.plot')
        self.log.debug( "Plot Init: #%X %r#%X %r#%X" %
                            (id(self), boat, id(boat), data, id(data)) )
        self.owner = boat
        if data is not None:
            self.data = data
        else:
            self.data = []
            
    def __del__(self):
        self.log.debug( "Plot Del : #%X %r#%X %r#%X" %
                        (id(self), self.owner, id(self.owner),
                         self.data, id(self.data)) )
        
    def __str__(self):
        return str(self.data)
    
    def __repr__(self):
        return 'plot(%r, %r)' % (self.owner, self.data)
    
    def __setitem__(self, item, value):
        old = self.data[:]
        self.data[item] = value
        self.__validate(old)
        
    def __getitem__(self, item):
        return self.data[item]
    
    def __delitem__(self, item):
        old = self.data[:]
        self.data.__delitem__(item)
        self.__validate(old)
        
    def __len__(self):
        return len(self.data)
    
    def __iter__(self):
        for i in self.data:
            yield i
            
    def append(self, item):
        old = self.data[:]
        self.data += [item]
        self.__validate(old)
        
    def __iadd__(self, item):
        old = self.data[:]
        self.data += item
        self.__validate(old)
        return self
    
    def __validate(self, backup):
        try:
            self.owner.validatePlot()
        except:
            ## JEB: Why do you remove the last item?
            self.data = backup
            raise

class move(object):
    """
    Represents a segment of a plotted move.
    """
    direction = North
    distance = 0
    
    def __init__(self, odir=North, dist=0):
        self.direction = odir
        self.distance = dist
    
    def __str__(self):
        return '%0.1f" %s' %(self.distance, self.direction)
    
    def __repr__(self):
        return 'move(%r, %r)' % (self.direction, self.distance)
    
    def _getdir(self):
        return self.direction
    
    def _setdir(self, value):
        self.direction = value
    dir = property(_getdir, _setdir)
    
    def _getdist(self):
        return self.distance
    
    def _setdist(self, value):
        self.distance = value
    dist = property(_getdist, _setdist)


